<template>
  <div class="image-gen-container">
    <!-- ========== 首次提问前的居中欢迎态 ========== -->
    <div v-if="chatHistory.length === 0" class="welcome-box">

      <h1 class="welcome-title">AIBOT</h1>

      <!-- 输入区（直接搬过来） -->
      <div class="input-area welcome-input">
        <div class="input-wrapper" style="margin-left: 23%">
          <el-input
              v-model="askImgText"
              type="textarea"
              :rows="3"
              placeholder="描述你想要的图片，例如：一片宁静的湖泊，远处有雪山，蓝天白云，油画风格..."
              class="chat-input"
              resize="none"
              @keydown.enter.prevent="handleEnter"
          />
          <div class="input-actions">
            <el-select v-model="imageCount" placeholder="数量" style="width: 80px">
              <el-option :value="1" label="1张"/>
              <el-option :value="2" label="2张"/>
              <el-option :value="3" label="3张"/>
              <el-option :value="4" label="4张"/>
            </el-select>

            <el-button
                type="primary"
                @click="aiAskImg"
                :loading="loading"
                class="send-button"
            >
              <el-icon v-if="!loading"><Position /></el-icon>
              <span v-else>生成中...</span>
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- ========== 原聊天界面（发出第一条后显示） ========== -->
    <template v-else>
      <!-- 聊天历史 -->
      <div class="chat-history" ref="chatHistory">
        <div
            v-for="(message, index) in chatHistory"
            :key="index"
            class="chat-message"
            :class="message.type"
        >
          <!-- 用户消息 -->
          <div v-if="message.type === 'user'" class="message-content user-message">
            <div class="message-bubble">
              <div class="message-text">{{ message.content }}</div>
              <div class="message-time">{{ formatTime(message.timestamp) }}</div>
            </div>
            <div class="avatar user-avatar">
              <el-icon><User /></el-icon>
            </div>
          </div>

          <!-- AI消息 -->
          <div v-else class="message-content ai-message">
            <div class="avatar ai-avatar">
              <el-icon><Picture /></el-icon>
            </div>
            <div class="message-bubble">
              <div class="message-text">{{ message.content }}</div>
              <div class="images-grid" v-if="message.images && message.images.length > 0">
                <div
                    v-for="(img, imgIndex) in message.images"
                    :key="imgIndex"
                    class="generated-image-wrapper"
                    @click="previewImage(img)"
                >
                  <img :src="img" class="generated-image" alt="AI生成图片">
                  <div class="image-overlay">
                    <el-button type="primary" size="small" @click.stop="downloadImage(img)">
                      <el-icon><Download /></el-icon>下载
                    </el-button>
                  </div>
                </div>
              </div>
              <div class="message-time">{{ formatTime(message.timestamp) }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="input-area">
        <div class="input-wrapper">
          <el-input
              v-model="askImgText"
              type="textarea"
              :rows="3"
              placeholder="描述你想要的图片，例如：一片宁静的湖泊，远处有雪山，蓝天白云，油画风格..."
              class="chat-input"
              resize="none"
              @keydown.enter.prevent="handleEnter"
          />
          <div class="input-actions">
            <el-select v-model="imageCount" placeholder="数量" style="width: 80px">
              <el-option :value="1" label="1张"/>
              <el-option :value="2" label="2张"/>
              <el-option :value="3" label="3张"/>
              <el-option :value="4" label="4张"/>
            </el-select>

            <el-button
                type="primary"
                @click="aiAskImg"
                :loading="loading"
                class="send-button"
            >
              <el-icon v-if="!loading"><Position /></el-icon>
              <span v-else>生成中...</span>
            </el-button>
          </div>
        </div>
      </div>
    </template>

    <!-- 图片预览对话框 -->
    <el-dialog
        v-model="previewVisible"
        :show-close="false"
        width="80%"
        top="5vh"
        class="image-preview-dialog"
    >
      <img :src="previewImageUrl" class="preview-image" alt="预览图片">
      <template #footer>
        <div class="preview-actions">
          <el-button @click="previewVisible = false">关闭</el-button>
          <el-button type="primary" @click="downloadImage(previewImageUrl)">
            <el-icon><Download /></el-icon>下载
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from '../api/index.js';
import { ElMessage } from 'element-plus';
import {
  User,
  Picture,
  Position,
  Download,
  Close
} from '@element-plus/icons-vue';

export default {
  name: 'ImageGen',
  components: {
    User,
    Picture,
    Position,
    Download,
    Close
  },
  data() {
    return {
      askImgText: '',
      imageCount: 1,
      chatHistory: [],
      loading: false,
      previewVisible: false,
      previewImageUrl: '',
      checkImageTimer: null,
      dialogVisible: false,
    };
  },
  methods: {
    handleEnter(event) {
      if (!event.shiftKey) {
        this.aiAskImg();
      }
    },

    // 修复 aiAskImg 方法
    async aiAskImg() {
      if (!this.askImgText.trim()) {
        this.showDialog('请输入作图描述');
        return;
      }

      // 清理之前的定时器
      if (this.checkImageTimer) {
        clearInterval(this.checkImageTimer);
        this.checkImageTimer = null;
      }

      /* ① 缓存用户输入 */
      const userPrompt = this.askImgText.trim();
      /* ② 立即清空输入框 */
      this.askImgText = '';
      /* ③ 把用户对话插到历史 */
      this.chatHistory.push({
        type: 'user',
        content: userPrompt,
        timestamp: new Date()
      });

      this.loading = true;
      try {
        const params = new URLSearchParams();
        params.append('ask', userPrompt);
        params.append('num', this.imageCount);

        const taskId = await axios.post('/ai/image/create2', params, {
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        });

        if (!taskId) throw new Error('未获取到任务ID');

        /* ⑤ 插入"正在生成"占位消息 */
        this.chatHistory.push({
          type: 'ai',
          content: '正在生成图片...',
          timestamp: new Date(),
          images: []
        });

        // 启动定时器检查图片状态
        this.checkImageTimer = setInterval(() => {
          this.checkImageStatus(taskId);
        }, 2000);
      } catch (error) {
        console.error('AI作图请求失败:', error);
        this.showDialog('AI作图请求失败，请重试');
        this.loading = false;

        // 出错时清理定时器
        if (this.checkImageTimer) {
          clearInterval(this.checkImageTimer);
          this.checkImageTimer = null;
        }
      }
    },

    // 修复 checkImageStatus 方法
    async checkImageStatus(taskId) {
      try {
        const images = await axios.get('/ai/image/imgstatus', {
          params: { taskId }
        });

        if (images && images.length > 0) {
          // 更新最后一条AI消息
          const lastMessage = this.chatHistory[this.chatHistory.length - 1];
          if (lastMessage.type === 'ai') {
            lastMessage.content = `已生成 ${images.length} 张图片`;
            lastMessage.images = images;
          }

          // 清理定时器
          if (this.checkImageTimer) {
            clearInterval(this.checkImageTimer);
            this.checkImageTimer = null;
          }

          this.loading = false;

          this.$nextTick(() => {
            this.scrollToBottom();
          });
        }
      } catch (error) {
        console.error('查询图片状态失败:', error);
        ElMessage.error('图片生成失败，请重试');

        // 出错时清理定时器
        if (this.checkImageTimer) {
          clearInterval(this.checkImageTimer);
          this.checkImageTimer = null;
        }

        this.loading = false;
      }
    },

    previewImage(url) {
      this.previewImageUrl = url;
      this.previewVisible = true;
    },

    downloadImage(imgUrl) {
      const link = document.createElement('a');
      link.href = imgUrl;
      link.download = `ai-image-${Date.now()}.png`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      ElMessage.success('图片下载成功');
    },

    formatTime(date) {
      if (!(date instanceof Date)) date = new Date(date);
      const y = date.getFullYear();
      const m = String(date.getMonth() + 1).padStart(2, '0');
      const d = String(date.getDate()).padStart(2, '0');
      const h = String(date.getHours()).padStart(2, '0');
      const min = String(date.getMinutes()).padStart(2, '0');
      const s = String(date.getSeconds()).padStart(2, '0');
      return `${y}-${m}-${d} ${h}:${min}:${s}`;
    },

    scrollToBottom() {
      const container = this.$refs.chatHistory;
      if (container) container.scrollTop = container.scrollHeight;
    },

    showDialog(msg) {
      ElMessage.warning(msg);
    }
  },

  beforeUnmount() {
    if (this.checkImageTimer) {
      clearInterval(this.checkImageTimer);
      this.checkImageTimer = null;
    }
  }
};
</script>

<style scoped>
.image-gen-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
}

.chat-message {
  margin-bottom: 20px;
}

.message-content {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.user-message {
  justify-content: flex-end;
}

.ai-message {
  justify-content: flex-start;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.user-avatar {
  background: #409eff;
  color: white;
}

.ai-avatar {
  background: #67c23a;
  color: white;
}

.message-bubble {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 18px;
  position: relative;
}

.user-message .message-bubble {
  background: #409eff;
  color: white;
  border-bottom-right-radius: 4px;
}

.ai-message .message-bubble {
  background: white;
  color: #333;
  border-bottom-left-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.message-text {
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 4px;
}

.message-time {
  font-size: 12px;
  opacity: 0.6;
}

.images-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 10px;
  margin-top: 10px;
}

.generated-image-wrapper {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.2s;
}

.generated-image-wrapper:hover {
  transform: scale(1.05);
}

.generated-image {
  width: 100%;
  height: 150px;
  object-fit: cover;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.2s;
}

.generated-image-wrapper:hover .image-overlay {
  opacity: 1;
}

.input-area {
  padding: 20px;
  background: white;
  border-top: 1px solid #eee;
}

.input-wrapper {
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

.chat-input {
  flex: 1;
}

.chat-input :deep(.el-textarea__inner) {
  border-radius: 20px;
  padding: 12px 16px;
  border: 1px solid #dcdfe6;
  transition: border-color 0.2s;
}

.chat-input :deep(.el-textarea__inner:focus) {
  border-color: #409eff;
}

.input-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.send-button {
  border-radius: 50%;
  width: 40px;
  height: 40px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-preview-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.preview-image {
  width: 100%;
  height: auto;
  max-height: 70vh;
  object-fit: contain;
}

.preview-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px;
}

.chat-history::-webkit-scrollbar {
  width: 6px;
}
.chat-history::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
}
.chat-history::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 3px;
}
.chat-history::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}

@media (max-width: 768px) {
  .message-bubble {
    max-width: 85%;
  }
  .images-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

/* ========== 新增：欢迎态样式 ========== */
.welcome-box {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.welcome-title {
  font-size: 56px;
  font-weight: 600;
  color: black;
  margin-bottom: 32px;
  letter-spacing: 2px;
}
.welcome-input {
  width: 600px;
  max-width: 90vw;
}
</style>